import React, {useEffect, useState} from "react";
import {getExerciseList} from "../../services/exercise";
import cloneDeep from "lodash/cloneDeep"
import {addTaskExerciseItem, delTaskExerciseItem, setTaskExerciseList} from "../../actions";
import {connect} from "react-redux";
import { GlobalEventEmitter } from "../../common/event"
function MainContent(props) {
    const { taskExerciseList, addTaskExerciseItem,delTaskExerciseItem,changeNotify } = props;
    const [exerciseList, setExerciseList] = useState([])

    useEffect(() => {
        setExerciseList(getExerciseList(5))
        GlobalEventEmitter.on('taskChange', msg => {
            console.log('发生了改变')
        })
    }, [])




    function handleClick(item,index) {
        if (item.selected) {
           exerciseList[index].selected = false;
           delTaskExerciseItem(item.id);
            console.log('delTaskExerciseItem---', taskExerciseList)
        } else {
            exerciseList[index].selected = true;
            addTaskExerciseItem(item);
            console.log('addTaskExerciseItem---', taskExerciseList)
        }
        setExerciseList(cloneDeep(exerciseList));
    }

    return (<div className="container-fluid">
        <table className="table">
            <thead>
                <tr>
                    <th>内容</th>
                    <th>名称</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            {
                exerciseList.map((item,index) => {
                    return <tr key={item.id}>
                        <th scope="row">{item.content}</th>
                        <td>{item.name}</td>
                        <td>
                            <button type="button" className={`btn ${item.selected ? 'btn-danger' : 'btn-primary'}`}
                                    onClick={() => {
                                        handleClick(item,index)
                                    }}>{item.selected ? '移除' : '添加'}</button>
                        </td>
                    </tr>
                })
            }
            </tbody>
        </table>
    </div>)
}

function mapStateToProps(state) {
    return {
        taskExerciseList: state.exercise
    }
}

function mapDispatchToProps(dispatch) {
    return {
        setTaskExerciseList: (list) => dispatch(setTaskExerciseList(list)),
        addTaskExerciseItem: item => dispatch(addTaskExerciseItem(item)),
        delTaskExerciseItem: id => dispatch(delTaskExerciseItem(id))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MainContent);
